// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

const db = cloud.database()//引用云数据库
const account = db.collection("account")
const _ = db.command
// 云函数入口函数
// 登录函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  let myScore, rankingArray, myRanking, topScoreSort
  if (event.type == 'topScore') {
    // 单局最高分排行
    myScore = await account.where({
      openid: wxContext.OPENID
    }).get()
    rankingArray = await account
      .field({ topScore: true, openid: true })
      .orderBy('topScore', 'desc')
      .get()
    myRanking = rankingArray.data.findIndex(item => item.openid === wxContext.OPENID)
    topScoreSort = await account
      .field({ topScore: true, userInfo: true })
      .limit(100)
      .orderBy('topScore', 'desc')
      .get()

  } else if (event.type == 'passNumber') {
    // 总过关次数排行
    myScore = await account.where({
      openid: wxContext.OPENID
    }).get()
    rankingArray = await account
      .field({ passNumber: true, openid: true })
      .orderBy('passNumber', 'desc')
      .get()
    myRanking = rankingArray.data.findIndex(item => item.openid === wxContext.OPENID)
    topScoreSort = await account
      .where({
        passNumber: _.gt(0)
      })
      .field({ passNumber: true, userInfo: true })
      .limit(100)
      .orderBy('passNumber', 'desc')
      .get()
  } else if (event.type == 'dayPassNumber') {
    // 今日过关次数排行
    myScore = await account.where({
      openid: wxContext.OPENID
    }).get()
    rankingArray = await account
      .field({ dayPassNumber: true, openid: true })
      .orderBy('dayPassNumber', 'desc')
      .get()
    myRanking = rankingArray.data.findIndex(item => item.openid === wxContext.OPENID)
    topScoreSort = await account
      .where({
        dayPassNumber: _.gt(0)
      })
      .field({ dayPassNumber: true, userInfo: true })
      .limit(100)
      .orderBy('dayPassNumber', 'desc')
      .get()
  }
  const returnData = {
    myScore: {
      ranking: myRanking,
      topScore: myScore.data[0].topScore,
      passNumber: myScore.data[0].passNumber,
      userInfo: myScore.data[0].userInfo,
      dayPassNumber: myScore.data[0].dayPassNumber
    },
    topScoreSort: topScoreSort.data
  }

  return {
    code: 'shouQuan',
    res: returnData
  }

}
